package io.xxx.aurora.netty

import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelInboundHandlerAdapter
import io.netty.util.ReferenceCountUtil
import java.nio.ByteBuffer
import java.nio.channels.FileChannel
import java.nio.file.Paths
import java.nio.file.StandardOpenOption

/**
 * 处理客户端请求
 */
class ServerHandler : ChannelInboundHandlerAdapter() {

    private val fc: FileChannel

    init {
        val path = Paths.get("~/000.log")
        this.fc = FileChannel.open(path, StandardOpenOption.READ, StandardOpenOption.WRITE)
    }

    override fun channelRead(ctx: ChannelHandlerContext, msg: Any) {
        val inBuf = msg as ByteBuf
        try {
            while (inBuf.isReadable) {
                val dst = ByteArray(1024)
                val bytes = inBuf.readBytes(dst)
                print(inBuf.readByte().toInt().toChar())
                val byteBuffer = ByteBuffer.allocate(bytes.array().size)
                fc.write(byteBuffer)
            }
        } finally {
            ReferenceCountUtil.release(msg)
        }
    }
}